<template>
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="60%" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #deptName="{ model, field, label, componentProps }">
        <ApiSelect mode="single" v-model:value="model[field]" :placeholder="'请选择'" resultField='data'
          labelField='deptName' valueField='deptName' :api=ywDeptSelectList
          @change="(value, row) => { handleSuccess({ value, row }, model, field) }">
        </ApiSelect>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm, ApiSelect } from '@/components/Form';
import { formSchema } from './role.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicTree, TreeItem } from '@/components/Tree';
import { commissionConfigSave } from '@/api/heng/ywManage';
import Ainput from '@/views/bookManage/components/account/Ainput.vue';
import { ywDeptSelectList } from '@/api/heng/ywManage';

import { useMessage } from "@/hooks/web/useMessage";

import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);
const { createMessage } = useMessage();

const id = ref("");
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  labelCol: { span: 5 },
  // baseColProps: { lg: 12, md: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  resetFields();
  setModalProps({ confirmLoading: false });
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  // if (unref(treeData).length === 0) {
  //   treeData.value = (await getMenuList()) as any as TreeItem[];
  // }
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  if (unref(isUpdate)) {

    // console.log("---data.record:",data.record)
    id.value = data.record.commissionId;

    setFieldsValue(data.record);


  } else {
    //新增

    userStore.setChatIsUpdate(false);

  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增业务部门抽成点数' : '编辑业务部门抽成点数'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    // TODO custom api
    values.commissionId = id.value;

    // console.log("---handleSubmit::isUpdate", isUpdate.value)
    // if (isUpdate.value) {
    //   editFn(values);
    // }else{
    //   createFn(values)
    // }
    if (!values.manageUserRate) {
      values.manageUserRate = 0;
    }
    if (!values.xiangmuGroupRate) {
      values.xiangmuGroupRate = 0;
    }
    createFn(values);
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

function createFn(values) {
  commissionConfigSave(values).then((res) => {
    // console.log("---res::",res)
    if (res.code == 200) {
      createMessage.success(res.message);
    } else {
      createMessage.error(res.message);
    }
  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      closeModal();
      emit('success');
    });
}

function editFn(values) {
  ywGroupSave(values).then((res) => {
    // console.log("---res::",res)
    if (res.code == 200) {
      createMessage.success(res.message);
    } else {
      createMessage.error(res.message);
    }
  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      closeModal();
      emit('success');
    });
}

function handleSuccess({ value, row }, model, field) {
  // console.log("---handleSuccess:", value, row);
  model[field] = value;
  model.deptId = row.deptId;
  model.deptNo = row.deptNo;
  //  ywGroupDetail({groupId:row.groupId}).then((res) => {
  //   // console.log("---res::",res)
  //   if (res.code == 200) {

  //   } else {

  //   }
  // })
  // model[field] = e.names;

}

</script>
